var mainAttrid="mainAttr";
var pedit_salenum=0;
var pedit_saleattrs=[];

//添加到销售列表
function pedit_addsale(){
	var str="";
	var ids="";
	$(".saleattr",$("#saleattrspanel")).each(function(){
		var id=this.id;
		var attrtxt="";
		var attrcode="";
		if($(this).attr("attrtype")=="3"){
			//多选复选框
			$getByName("bean."+id,$(this)).each(function(){
				if(this.checked){
					if(attrtxt!="")attrtxt+=",";
					if(attrcode!="")attrcode+=",";
					attrtxt+=$(this).parent().text();
					attrcode+=this.value;
				}
			})
			$getByName("bean."+id,$(this)).each(function(){this.checked=false})
		}
		if(attrtxt!=""){
			attrtxt=$(this).prev().text().replace("：",":")+"["+attrtxt+"]";
			if(str!="")str+="、";
			str+=attrtxt;
		}
		if(attrcode!=""){
			attrcode=id.replace("attrs_","")+":"+attrcode;
			if(ids!="")ids+="|";
			ids+=attrcode;
		}
	})
	if(str){
		pedit_salenum++;
		pedit_addsaletr(pedit_salenum,ids,str,'','','','');
	}
}
//增加销售属性信息
function pedit_addsaletr(aid,ids,a,b,c,d,e,imgs,saveid){
	var attrid=aid;
	if(ids=="0")attrid=mainAttrid;
	var attrobj=new Object();
	attrobj.id=attrid;
	attrobj.attrids=ids;
	attrobj.photoids=[];
	pedit_saleattrs.push(attrobj);
	var tr='<tr style="background: #ffffff" id="saleattvals'+attrid+'">'
		+'<td align="center" height="30"><input name="saleattr_id" type="hidden" value="'+(saveid || '')+'"><input name="saleattr_ids" type="hidden" value="'+ids+'">'+((attrid==mainAttrid)?"商品销售":a)+'</td>'
		+'<td align="center"><input name="saleattr_price_s" style="width:90%" disabled="true" value="'+b+'" onkeyup="inputMonery(this)"></td>'
		+'<td align="center"><input name="saleattr_price" style="width:90%" disabled="true" value="'+c+'" onkeyup="inputMonery(this)"></td>'
        +'<td align="center"><input name="saleattr_amount" style="width:90%" disabled="true" value="'+d+'" onkeyup="inputNumber(this)"></td>'
        +'<td align="center"><input name="saleattr_djamount" style="width:90%" disabled="true" value="'+e+'" ></td>'
		+'<td align="center"><a href="javascript:;" onclick="pedit_delsaletr(this,\''+attrid+'\')"><img src="'+ctx+'/platform/images/cross.png"></a></td>'
		+'</tr>';
	$("#saleattrstb").append(tr);
	pedit_addimgtr(a,attrid,imgs);
}
var pedit_num=0;
var pedit_uploaders=[];
function pedit_addimgtr(name,attrid,imgs){
	var upid="peditup"+pedit_num;
	var h='<tr style="background:#ffffff" imgattrid="'+attrid+'">'
		+'<td class="label" width="200" style="padding-bottom:10px;text-align:center">'+((attrid==mainAttrid)?"商品图片":name)+'：<br/><a href="javascript:;" id="'+upid+'" class="ui_btn" style="margin-right:8px;">选择图片</a></td>'
		+'<td class="val"><div style="height:64px;overflow-y:hidden">'
		+'<div class="gridly">';
		if(imgs){
			$(imgs).each(function(){
				h+="<div class='brickpic pl_upimgdiv' id='img_"+this.id+"' attrid='"+attrid+"'><img src='"+fileserver+this.viewpath+"' /><input name='productphotos' type='hidden' value='"+this.id+"'/><i class='remove' onclick='pedit_delup(this)'></i></div>";
			})
		}
		h+='</div>'
		+'</div></td>'
		+'</tr>';
	$("#pedit_imgtb").append(h);
	$('.gridly',$("#"+upid).parent().next()).gridly({callbacks:{ reordered:pedit_reordered}});
	
	var plparm={
			runtimes : 'html5,flash,silverlight,html4',
			browse_button :upid,
		    multi_selection: true,
			flash_swf_url : ctx+'/plugins/plupload2/Moxie.swf',
			silverlight_xap_url : ctx+'/plugins/plupload2/Moxie.xap',
		    url : '',
		    filters: {
				max_file_size : '500kb',
				prevent_duplicates :false, //不允许选取重复文件
			  	mime_types : [ //只允许上传图片文件
			    { title : "图片文件", extensions : "jpg,png,jpeg,gif" }
			  	]
			},
			init: {
				FilesAdded: function(up, files) {
					var upobj=pedit_getuploader(up.id);
					var gridlypar=$("#"+upobj.id).parent().next();
					if(files.length>0)pedit_prewn--;
					for(var i=0;i<files.length;i++){
						pedit_loadfs.push(files[i]);
						var html="<div class='brickpic pl_upimgdiv' id='img_"+files[i].id+"' attrid='"+attrid+"'><img src='"+ctx+"/images/imgloading.png' /><input name='productphotos' type='hidden'/><div class='progressbg'></div><div class='progresstxt'>等待上传</div><i class='remove' onclick=\"pedit_delup(this,'"+up.id+"')\"></i></div>";
						$(".gridly",gridlypar).append(html);
					}
					pedit_loadprew();
					$('.gridly',gridlypar).gridly({callbacks:{ reordered:pedit_reordered}});
                    pedit_upload();
				},UploadFile:function(up,file){
					var f=$('#img_'+file.id);
					$(".progresstxt",f).show();
				},UploadProgress:function(up,file){
					var f=$('#img_'+file.id);
					var d=$(".progressbg",f);
					var w=f.width()*parseInt(file.percent)/100;
					d.css("width",w+"px");
					$(".progresstxt",f).html(file.percent+"%");
				},FileUploaded:function(up,file,responseObject){
					var re=jQuery.parseJSON(responseObject.response);
					$("input",$('#img_'+file.id)).val(re.fileid);
                    $("img",$('#img_'+file.id)).attr("src",re.url);
				},UploadComplete:function(){
				}
			}
	}
	$oss.setUpDir("products");
	var uploader=$oss.initUpload(plparm);
	pedit_uploaders.push({"id":upid,attrid:attrid,"uploader":uploader});
	pedit_num++;
}
function pedit_getuploader(uploaderid){
	for(var i=0;i<pedit_uploaders.length;i++){
		if(pedit_uploaders[i].uploader.id==uploaderid)
			return pedit_uploaders[i];
	}
}

function pedit_delsaletr(obj,attrid){
	$(obj).parent().parent().remove();
	for(var i=0;i<pedit_saleattrs.length;i++){
		if(pedit_saleattrs[i].id==attrid){
			pedit_saleattrs.splice(i,1);
			break;
		}
	}
	for(var i=0;i<pedit_uploaders.length;i++){
		if(pedit_uploaders[i].attrid==attrid){
			pedit_uploaders.splice(i,1);
			break;
		}
	}
	$("[imgattrid='"+attrid+"']").remove();
}

function pedit_delup(obj,upid){
	if(upid){
		var upobj=pedit_getuploader(upid);
		var fileid=$(obj).parent().attr("id");
		fileid=fileid.replace("img_","");
		var file=upobj.uploader.getFile(fileid);
		upobj.uploader.removeFile(file);
	}
	$(obj).parent().remove();
}

//图片拖动排序回调函数
function pedit_reordered(elements){
	try{
	 	var arr = elements;
		var photos=[];
		//将顺序加入pedit_saleattrs数值
		var saleattrobj;
		for(i =0; i < arr.length; i++){ 
			var attrid=$(arr[i]).attr("attrid");
				for(var n=0;n<pedit_saleattrs.length;n++){
					if(pedit_saleattrs[n].id==attrid){
						saleattrobj=pedit_saleattrs[n];
						break;
					}
				}
		 	photos.push(arr[i].id);
		}
		saleattrobj.photoids=photos;
	}catch(e){}
}
var pedit_loadfs=[];
var pedit_fr;
var pedit_prewn=0;
function previewImages(file,callback){
	if(!file || !/image\//.test(file.type)) return;
	if(file.type=='image/gif'){
		var fr = new mOxie.FileReader();
		fr.onload = function(){
			callback(fr.result);
		}
		fr.readAsDataURL(file.getSource());
	}else{
		var preloader = new mOxie.Image();
		preloader.onload = function() {
			preloader.downsize( 100, 100 );
			var imgsrc = preloader.type=='image/jpeg' ? preloader.getAsDataURL('image/jpeg',80) : preloader.getAsDataURL();
			callback && callback(imgsrc); 
			preloader.destroy();
			preloader = null;
		};
		preloader.load( file.getSource() );
	}	
}
//生成预览图
function pedit_loadprew(){
	pedit_prewn++;
	if(pedit_prewn<pedit_loadfs.length){
		previewImages(pedit_loadfs[pedit_prewn],function(imgsrc){
			$("img",$("#img_"+pedit_loadfs[pedit_prewn].id)).attr('src',imgsrc);
			if(pedit_fr){
				pedit_fr.destroy();
				pedit_fr = null;
			}
			pedit_loadprew();
		})
	}
}
var pedit_uploadcur=0;
function pedit_uploadnext(){
	pedit_uploadcur++;
	if(pedit_uploadcur<=pedit_uploaders.length){
		if(pedit_uploaders[pedit_uploadcur-1].uploader.files.length>0){
		
			pedit_uploaders[pedit_uploadcur-1].uploader.start();
		}
		else pedit_uploadnext();
	}else pedit_saveProduct();//上传图片完毕，保存数据
	
}
function pedit_upload(){
    pedit_uploadcur=0;
    pedit_uploadcur++;
    if(pedit_uploadcur<=pedit_uploaders.length){
        if(pedit_uploaders[pedit_uploadcur-1].uploader.files.length>0){

            pedit_uploaders[pedit_uploadcur-1].uploader.start();
        }
        else pedit_upload();
    }
}
//点击保存按钮
function pedit_uploaddata(){
	/*pedit_uploadcur=0;
	$.messager.progress();
	if(pedit_uploaders.length>0){
		pedit_uploadnext();
	}else pedit_saveProduct();*/

    $.messager.progress();
    pedit_saveProduct();
}
//保存数据
var pedit_saveing=false;
function pedit_saveProduct(){
	if($getByName("bean.name",$w.currWin()).val()==''){
		window.parent.$w.alertMsg("请输入商品名称");
		$.messager.progress('close');
		return false;
	}
	/*if($("[attrid='"+mainAttrid+"']").length==0){
		window.parent.$w.alertMsg("请上传商品图片");
		$.messager.progress('close');
		return false;
	}*/
	if(!pedit_saveing){
		pedit_saveing=true;//防止重复保存
		var data=pedit_getdata();
		$w.doUrl(ctx+"/products/ProductPage@update.page",data,function(ret){
			pedit_uploadcur=0;
			pedit_saveing=false;
			$.messager.progress('close');
			if(ret.state=='ok'){
				window.parent.$w.correctMsg("保存商品成功");
				$w.closeCurrWin("ok");
			}else window.parent.$w.alertMsg(ret.state);
		})
	}
}
//组装数据
function pedit_getdata(){
	var win=$w.currWin();
	var data={"bean.id":$getByName("bean.id",win).val(),"bean.classid":$getByName("bean.classid",win).val()};
	//基本信息
	$(".beanval",win).each(function(){
		data[this.name]=this.value;
	})
	pedit_attrTodata(data);
	if(detail_editor)$("[name='bean.details']").val(detail_editor.html());
	data["bean.details"]=$("[name='bean.details']").val();
	if(book_editor)$("[name='bean.shuombook']").val(book_editor.html());
	data["bean.shuombook"]=$("[name='bean.shuombook']").val();
	if(aboutus_editor)$("[name='bean.aboutus']").val(aboutus_editor.html());
	data["bean.aboutus"]=$("[name='bean.aboutus']").val();
	var controlsales="";//控销数据
	var combox=$("#controlsales").get(0);
	for(var i=0;i<combox.options.length;i++){
		if(controlsales!="")controlsales+=",";
		controlsales+=combox.options[i].value;
	}
	data["bean.controlsales"]="["+controlsales+"]";
	var controlusers="";//控销用户
	$("[name='controluserid']").each(function(){
		controlusers+=this.value+",";
	})
	data["bean.controlusers"]=controlusers
	var gradeprices="";//价格等级
	$("[name='gradeprice']").each(function(){
		if(this.value!=""){
			if(gradeprices!="")gradeprices+=",";
			gradeprices+="{'grade':'"+$(this).attr("grade")+"','price':'"+this.value+"'}"
		}
	})
	data["bean.gradeprices"]="["+gradeprices+"]";
	return data;
}
//将属性值组装可提交数据
function pedit_attrTodata(data){
	$(".pattr",$w.currWin()).each(function(){
		var id=this.id;
		if($(this).attr("attrtype")=="3"){
			//多选复选框
			var vals="";
			$getByName("bean."+id,$(this)).each(function(){
				if(this.checked){
					if(vals!="")vals+=",";
					vals+=this.value;
				}
			})
			data["bean."+id]=vals;
		}else{
			data["bean."+id]=$getByName("bean."+id,$(this)).val();
		}
		
		
	})
	
	//组装销售属性信息
	var saleattrstr="[";
	for(var i=0;i<pedit_saleattrs.length;i++){
		if(i!=0)saleattrstr+=",";
		var basea=$("#saleattvals"+pedit_saleattrs[i].id);
		saleattrstr+="{";
		saleattrstr+="\"id\":\""+$("[name='saleattr_id']",basea).val()+"\",";//如果已保存过的id
		saleattrstr+="\"attrcodes\":\""+pedit_saleattrs[i].attrids+"\",";
		saleattrstr+="\"price\":\""+$("[name='saleattr_price']",basea).val()+"\",";
		saleattrstr+="\"price_s\":\""+$("[name='saleattr_price_s']",basea).val()+"\",";
        saleattrstr+="\"amount\":\""+$("[name='saleattr_amount']",basea).val()+"\",";
        saleattrstr+="\"djamount\":\""+$("[name='saleattr_djamount']",basea).val()+"\",";
		var salephotostr="";//销售属性图片信息
		var salephotosarr = [];
		debugger;
        $(".gridly").find(".brickpic").each(function () {
            var salephotosa = {};
            salephotosa["salephotostr"] = $(this).find("input").val();
            var order = parseInt($(this).css("left"));
            salephotosa["orderno"] =order;
            salephotosarr.push(salephotosa);
        });
        var orderarr = salephotosarr.sort(function (a,b) {
			return a.orderno-b.orderno;
        });
        for(var i = 0;i<orderarr.length;i++) {
            if(salephotostr!="")salephotostr+=",";
            salephotostr+=orderarr[i].salephotostr;
        }
		/*if(pedit_saleattrs[i].photoids.length==0){
		 $("[attrid='"+pedit_saleattrs[i].id+"']").each(function(){
		 if(salephotostr!="")salephotostr+=",";
		 salephotostr+=$("input",$(this)).val();
		 })
		 }*/
		saleattrstr+="\"photos\":\""+salephotostr+"\"";
		saleattrstr+="}";
	}
	saleattrstr+="]";
	data["bean.saleattrs"]=saleattrstr;
	
}
//选择控销用户
function addControlUser(){
	window.parent.$w.openDialog({url:ctx+'/user/UserPage@userselQuery.page',title:"选择用户",w:800,h:450,afterClose:function(re){
		if(re && re.length>0){
			var tb=$("#controlusertb");
			for(var i=0;i<re.length;i++){
				var exist=false;
				tb.children().each(function(){
					if($("[name='controluserid']",$(this)).val()==re[i].id){
						exist=true;
						return false;
					}
				})
				if(!exist){
					var h='<tr class="ui_td">'
						+'<td align="center"><input name="controluserid" type="hidden" value="'+re[i].id+'">'+re[i].id+'</td>'
						+'<td align="center">'+re[i].loginname+'</td>'
						+'<td align="center">'+re[i].nickname+'</td>'
						+'<td>'+re[i].comname+'</td>'
						+'<td align="center">'+re[i].grade+'</td>'
						+'<td align="center"><a href="javascript:;" class="ui_btn_link" onclick="delcontroluser(this)">删除</a></td>'
						+'</tr>'
					tb.append(h);
				}
			}
			
		}
	}});
}
//删除控销用户
function delcontroluser(obj){
	$(obj).parent().parent().remove();
}
//添加控销
function addControlsales(){
	window.parent.$w.openDialog({url:ctx+'/products/ProductPage@addControlsalesShow.page',title:"控销",w:600,h:400,afterClose:function(ret){
		if(ret && ret.list.length>0){
			var txt="";
			var combox=$("#controlsales").get(0);
			for(var i=0;i<ret.list.length;i++){
				if(ret.type=="1")txt="客户分组："+ret.list[i].text;
				else if(ret.type=="2")txt="价格等级："+ret.list[i].text;
				else if(ret.type=="3")txt="区域控销："+ret.list[i].text;
				val="{'type':'"+ret.type+"','val':'"+ret.list[i].val+"','text':'"+txt+"'}";
			    combox.options[combox.options.length] = new Option(txt,val);
			}
		}
	}})
}
function delControlsales(){
	var combox=$("#controlsales").get(0);
	if(combox.options.length > 0)
    {
       for(var i=0;i<combox.options.length;i++)
       {
          var option = combox.options[i];
          if(option.selected)
          {
            combox.options[i]=null;
            i--;
          }
       }
    }
}